package com.sun.designPattern.Observer.ProjectImp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class EntityEventBlock extends Observable {
	private List<EntityChangeEvent> changeEvents = new ArrayList<EntityChangeEvent>();

	public void setObservers(List<Observer> observers) {//这里可以注入进来observer
		for (Observer observer : observers) {
			this.addObserver(observer);
		}
	}

	public static synchronized EntityEventBlock instance() {
		EntityEventBlock eventBlock = new EntityEventBlock();// from httpSession
		return eventBlock;
	}

	public void makeDelEvent(Class entityCls, Serializable id) {
		makeChangeEvent(entityCls, id, EntityChangeEvent.TYPE_DELETE);
	}

	public void makeAddEvent(Class entityCls, Serializable id) {
		makeChangeEvent(entityCls, id, EntityChangeEvent.TYPE_ADD);
	}

	public void makeUpdateEvent(Class entityCls, Serializable id) {
		makeChangeEvent(entityCls, id, EntityChangeEvent.TYPE_UPDATE);
	}

	private void makeChangeEvent(Class entityCls, Serializable id, int changeType) {
		EntityChangeEvent e = new EntityChangeEvent(entityCls, id, changeType);
		if (changeEvents.contains(e)) {
			changeEvents.remove(e);
		}
		changeEvents.add(e);
		this.setChanged();
	}

	public List<EntityChangeEvent> getChangeEvents() {
		return changeEvents;
	}

	public void setChangeEvents(List<EntityChangeEvent> changeEvents) {
		this.changeEvents = changeEvents;
	}
}
